package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    private static final String WECHAT_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 用户的登录方法
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
//调用getioenid方法，得到openid
        String openid = getOpenid(userLoginDTO);
//        如果不存在openid，则证明微信服务器校验失败
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
//        判断是否是第一次登录(调用mapper层根据openid查找)
        User user = userMapper.findByOpenid(openid);
//        如果为空则添加
        if (user == null) {
//            添加
            user = new User();
            user.setOpenid(openid);
            user.setName(UUID.randomUUID().toString().replace("-", ""));
            user.setCreateTime(LocalDateTime.now());
//            插入到表并主键返回
            userMapper.insert(user);
        }
        ;
//        不为空则返回
        return user;
    }

    public String getOpenid(UserLoginDTO userLoginDTO) {
        //        新建一个map集合
        HashMap<String, String> map = new HashMap();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
//        新建一个httpclient对象

//        新建一个httpget请求
        String token = HttpClientUtil.doGet(WECHAT_URL, map);
//        使用client对象向微信服务器发请求
//        返回对象包含token，openid
//        取出openid，判断数据库是否包含
        JSONObject jsonObject = JSON.parseObject(token);
        String openid = jsonObject.get("openid").toString();
        return openid;
    }
}
